package com.ppd.yygh.sms.controller;

import com.alibaba.excel.util.StringUtils;
import com.ppd.yygh.common.result.Result;
import com.ppd.yygh.sms.service.SmsService;
import com.ppd.yygh.sms.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信发送API接口")
@RestController
@RequestMapping("/api/sms")
public class SmsApiController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //发送手机验证码
    @ApiOperation("发送手机验证码")
    @GetMapping("send/{phone}")
    public Result sendCode(@PathVariable String phone) {
        //从redis里获取验证码
        //key 手机号 value 验证码
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //如果从redis获取不到
        //生产验证码，
        code = RandomUtil.getSixBitRandom();
        //调用service方法，通过整合短信服务来进行发送
        boolean isSend = smsService.send(phone, code);
        //生成验证码放到redis里面，设置有效时间
        //2分种有效
        if (isSend) {
            redisTemplate.opsForValue().set(phone, code, 200, TimeUnit.MINUTES);
            return Result.ok();
        } else {
            return Result.fail().message("发送短信失败");
        }
    }
}
